package brian.android.mvc.bean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import brian.android.mvc.exception.BeanCreationException;
import brian.android.mvc.exception.IllegalConstructorParamException;
import brian.android.mvc.exception.NoBeanIdException;

@SuppressWarnings("unchecked")
public class BeanConstructor {
	private Class beanType;
	private boolean isSingleton;
	private Object[] parameters;
	private static final Class[] EMPTY_CLASS_ARRAY = new Class[]{};
	
	public BeanConstructor(Class beanType) {
		this(beanType, (Object[]) null);
	}

	public BeanConstructor(Class beanType, boolean isSingleton, Object ... parameters) {
		this.beanType = beanType;
		this.isSingleton = isSingleton;
		this.parameters = parameters;
	}
	
	public BeanConstructor(Class beanType, Object ... parameters) {
		this.beanType = beanType;
		this.parameters = parameters;
	}

	public Class getBeanType() {
		return beanType;
	}

	public Object[] getConstructorParameters() throws IllegalConstructorParamException {
		if (parameters == null) {
			return Collections.emptyList().toArray();
		} else {
			for (int i=0; i<parameters.length; i++) {
				Object parameter = parameters[i];
				if (parameter instanceof BeanProxy) {
					BeanProxy beanProxy = (BeanProxy) parameter;
					
						try {
							Object beanParam = BeanFactory.getBean(beanProxy.getBeanId());
							parameters[i] = beanParam;
						} catch (NoBeanIdException e) {
							throw new IllegalConstructorParamException(e.getMessage(), e);
						} catch (BeanCreationException e) {
							throw new IllegalConstructorParamException(e.getMessage(), e);
						}
				}
			}
			return parameters;
		}
	}

	public Class[] getConstructorParameterTypes() {
		if (parameters == null) {
			return EMPTY_CLASS_ARRAY;
		} else {
			List<Class> clazzs = new ArrayList<Class>();
			for (Object paramenter : parameters) {
				if (paramenter instanceof BeanProxy) {
					BeanProxy beanProxy = (BeanProxy) paramenter;
					clazzs.add(beanProxy.getBeanType());
				} else {
					clazzs.add(paramenter.getClass());
				}
			}
			
			return clazzs.toArray(EMPTY_CLASS_ARRAY);
		}
	}
	
	public boolean isSingleTon() {
		return isSingleton;
	}
}
